package com.liangtian.mdm.util;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字符串工具类
 *
 * @author Baozi
 */
public class StringUtil {


    /**
     * 使用默认分隔符 , 分割字符串
     * @param str
     * @return
     */
    public static List<String> splitAsList(String str) {
        return splitAsList(str, ",");
    }

    /**
     * 使用指定分割符将字符串分割为List
     *
     * @param str       原字符串
     * @param separator 分隔符
     * @return 分割完的列表
     */
    public static List<String> splitAsList(String str, String separator) {
        String[] split = StringUtils.split(str, separator);
        return split == null ? new ArrayList<>() : Arrays.asList(split);
    }

    /**
     * 拼接某属性的 get方法
     *
     * @param fieldName
     * @return String
     */
    public static String parGetName(String fieldName) {
        if (null == fieldName || "".equals(fieldName)) {
            return null;
        }
        int startIndex = 0;
        if (fieldName.charAt(0) == '_') {
            startIndex = 1;
        }
        return "get" + fieldName.substring(startIndex, startIndex + 1).toUpperCase() + fieldName.substring(startIndex + 1);
    }

    public static String escapeSql(Object val) {
        if (val == null || "".equals(val.toString().trim())) {
            return "";
        } else {
            return val.toString()
                    .replaceAll("'", "''");
//	        		.replaceAll("/", "//")
//	        		.replaceAll("%", "/%")
//	        		.replaceAll("_", "/_");
        }
    }

    public static String safeNull(Object val) {
        String ret = "null";
        if (val != null) {
            ret = String.valueOf(val).trim();
            if ("".equals(ret))
                ret = "null";
        }
        return ret;
    }

    public static String safeEmpty(Object val) {
        String ret = "";
        if (val != null) {
            ret = String.valueOf(val).trim();
        }
        return ret;
    }

    public static boolean isBlank(Object val) {
        boolean ret = true;
        if (val != null) {
            String v = String.valueOf(val).trim();
            if (!"".equals(v))
                ret = false;
        }
        return ret;
    }

//	public static String pattern = "yyyy-MM-dd HH:mm:ss";

    public static String dateToString(String pattern, java.util.Date date) {
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }
}
